package com.sllp.C71S3TsllpShop.web;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.sllp.C71S3TsllpShop.bean.BigType;
import com.sllp.C71S3TsllpShop.bean.Business;
import com.sllp.C71S3TsllpShop.bean.Car;
import com.sllp.C71S3TsllpShop.bean.Favorite;
import com.sllp.C71S3TsllpShop.bean.Product;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;
import com.sllp.C71S3TsllpShop.biz.impl.CarBizImpl;
import com.sllp.C71S3TsllpShop.biz.impl.FavoriteBizImpl;
import com.sllp.C71S3TsllpShop.dao.CarMapper;
import com.sllp.C71S3TsllpShop.dao.ProductMapper;
import com.sllp.C71S3TsllpShop.dao.UserMapper;

@Controller
public class ProductListAction{
	@Resource
	private ProductMapper pm;
	@Resource
	private UserMapper um;
	@Resource
	private CarBizImpl cbi;
	@Resource
	private FavoriteBizImpl fbi;
//	商品详情
	@GetMapping({"product.do","product"})
	public String toProduct(HttpSession session,
			@SessionAttribute("loginUser") User user1,
			@SessionAttribute("btlist") List<List<BigType>> lists,
			Integer id, Integer count,Integer specs,Timestamp joinTime,Integer user,Model m) {
		m.addAttribute("btlist", lists);
		m.addAttribute("loginUser", user1);
		Product sbp = pm.selectByPrimaryKey(id);
		List<Favorite> favoriteList = fbi.findfavorite(user1);
		//添加收藏
		for (int i=0; i<favoriteList.size();i++) {
			if(sbp.getId()==favoriteList.get(i).getProduct() && favoriteList.get(i).getState()==2) { 
				sbp.setIsFav(1);
				break;
			}else if(sbp.getId()==favoriteList.get(i).getProduct() && favoriteList.get(i).getState()==1) {
				sbp.setIsFav(0);
				break;
			} else if(sbp.getId()!=favoriteList.get(i).getProduct() && i==favoriteList.size()-1){
				sbp.setIsFav(0);
			}
		}
		m.addAttribute(sbp);
		System.out.println(sbp);
		//int i = sbi.addToCar(count, specs, joinTime, user);
		return "product";
	}
	
	@ResponseBody
	@PostMapping("add.do")
	public Result add(Car car,@SessionAttribute("loginUser") User user) {
		car.setUser(user.getId());
		Result i = cbi.addToCar(car);
		return i;
	}
	
	@ModelAttribute
	public void searchCar(@SessionAttribute("loginUser") User user,Model m) {
		if(user != null) {
			List<Car> clist=cbi.findCar(user);
			m.addAttribute("clist", clist);
		}
	}
}
